#include "elicon.h"
#include <QPaintEvent>
#include <QPainter>
#include <QPropertyAnimation>
#include <QSvgWidget>
#include "../../utils/svghelper.h"

ElIcon::ElIcon(const QString &fileName, QWidget *parent)
    : QWidget{parent}
{
    resize(16, 16);
    setFileName(fileName);
    hide(); // need to call show() explicitly to show the icon.
}

ElIcon &ElIcon::setFileName(const QString &fileName)
{
    if (_fileName == fileName)
        return *this;
    _fileName = fileName;
    if (_svgWidget != nullptr) {
        delete _svgWidget;
        _svgWidget = nullptr;
    }
    if (SvgHelper::isSvgFile(fileName)) {
        _svgWidget = new QSvgWidget(fileName, this);
        _svgWidget->resize(size());
    } else {
        _img.load(fileName);
        _img = _img.scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        update();
    }
    emit iconChanged(_fileName);
    return *this;
}

bool ElIcon::isNull() const
{
    return _svgWidget == nullptr && _img.isNull();
}

QColor ElIcon::background() const
{
    if (_svgWidget == nullptr)
        return Qt::transparent;
    return _bgColor;
}

bool ElIcon::fillBackground(const QColor &color)
{
    if (_svgWidget == nullptr || _bgColor == color)
        return false;
    _bgColor = color;
    auto data = SvgHelper::filled(_fileName, _bgColor);
    _svgWidget->load(data);
    return true;
}

void ElIcon::setRotatable(bool b)
{
    // avoid to set true repeatly
    delete _animRotate;
    _animRotate = nullptr;
    if (b) {
        _animRotate = new QPropertyAnimation(this, "angle", this);
        _animRotate->setDuration(1000);
        _animRotate->setEasingCurve(QEasingCurve::Linear);
        _animRotate->setStartValue(0);
        _animRotate->setEndValue(360);
        _animRotate->setLoopCount(-1);
    }
}

void ElIcon::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    if (_animRotate != nullptr) {
        painter.translate(width() / 2, height() / 2);
        painter.rotate(_angle);
        painter.drawImage(-width() / 2, -height() / 2, _img);
    } else {
        painter.drawImage(0, 0, _img);
    }
    e->accept();
}

void ElIcon::showEvent(QShowEvent *e)
{
    if (_animRotate != nullptr)
        _animRotate->start();
    if (_svgWidget != nullptr) {
        _svgWidget->show();
        e->accept();
        return;
    }
    e->accept();
}

void ElIcon::resizeEvent(QResizeEvent *e)
{
    if (_svgWidget != nullptr)
        _svgWidget->resize(size());
    else {
        _img = _img.scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        update();
    }
    e->accept();
}

qreal ElIcon::angle() const
{
    return _angle;
}

void ElIcon::setAngle(qreal angle)
{
    if (_angle == angle)
        return;
    _angle = angle;
    update();
}
